﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using AceMobile.Models;

namespace AceMobile.Controllers
{    
    public class AccountController : Controller
    {        
        
        // GET: /Account/
        
        public ActionResult LogOn()
        {
            if (Session["Login"] != null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
        [HttpPost]

        public ActionResult LogOn(AccountLogOn lg)//nhan lg khi an login o from login

        {
            if (ModelState.IsValid)//chek tai khoan va mat khau dung cu phap
            {
                //thoa man dieu kien
                MobileWebContext db = new MobileWebContext();
                var data = (from d in db.Accounts
                            join c in db.Roles on d.Role equals c
                            where d.UserName.Equals(lg.UserName) && d.Password.Equals(lg.Password)
                            select new { Role = c.Name }).ToList();//lay du lieu voi dk tk va mk 
                if (data.Count > 0)
                {
                    //neu tai khoan ton tai ta gan cho session
                    Session["Login"] = lg.UserName;
                    Session["Roles"] = data.First().Role;

                    //goi den ham GetRolesForUser o customroleprovider
                    FormsAuthentication.SetAuthCookie(lg.UserName, lg.RememberMe);
                    return RedirectToAction("Index", "Home");
                }
                ViewBag.mess = "Mật khẩu hoặc tài khoản không đúng";
                return View("LogOn");
            }
            ViewBag.mess = "Bạn phải điền cả hai trường mật khẩu và tài khoản";
            return View("LogOn");//neu khong dung cu phap thi quay lai form dang nhap bao loi
        }

        // GET: /Account/Register
        public ActionResult Register()
        {
            if (Session["Login"] != null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
        [HttpPost]
        public ActionResult Register(AccountRegister lg)
        {
            if (ModelState.IsValid)//chek tai khoan va mat khau dung cu phap
            {
                //thoa man dieu kien
                MobileWebContext db = new MobileWebContext();
                var data = (from d in db.Accounts
                            where d.UserName.Equals(lg.UserName)
                            select d).ToList();//lay du lieu voi dk tk va mk 
                if (data.Count > 0)
                {                    
                    ViewBag.mess = "Tài khoản đã tồn tại";
                    return View();
                }
                else if (data.Count == 0)
                {
                    Account ac = new Account()
                    {
                        UserName = lg.UserName,
                        Password = lg.Password, 
                        Address = lg.Address,
                        Email = lg.Email,     
                        MobilePhone = lg.MobilePhone,
                        SecretQuestion = lg.SecretQuestion,
                        Role = db.Roles.Where(a => a.Name == "Customer").First()
                    };
                    db.Accounts.Add(ac);
                    db.SaveChanges();
                    //neu tai khoan da tao xong ta gan cho session
                    Session["Login"] = ac.UserName;
                    Session["Roles"] = ac.Role.Name;

                    //goi den ham GetRolesForUser o customroleprovider
                    FormsAuthentication.SetAuthCookie(lg.UserName, true);
                    
                    return RedirectToAction("Welcome", "Account");
                    
                }
                ViewBag.mess = "Xảy ra lỗi hệ thống";
                return View("LogOn");
            }
            ViewBag.mess = "Bạn phải điền vào các trường trên";
            return View();
        }


        public ActionResult ChangePassword()
        {
            if (Session["Login"] == null)
            {
                return RedirectToAction("LogOn");
            }
            return View();
        }
        [HttpPost]
        public ActionResult ChangePassword(AccountChangePassword lg)
        {
            if (Session["Login"]!=null) // Nếu chưa đăng nhập thì chuyển về LogOn action
            {
                if (ModelState.IsValid)
                {                    
                    MobileWebContext db = new MobileWebContext();
                    string username = Session["Login"].ToString();

                    var data = (from d in db.Accounts
                                where d.UserName.Equals(username)
                                select d).Single();
                    if (!data.Password.Equals(lg.OldPassword))
                    {                        
                        ViewBag.mess = "Mật khẩu cũ sai";
                        return View();
                    }
                    if (!lg.NewPassword.Equals(lg.NewPasswordConfirm))
                    {                        
                        ViewBag.mess = "Mật khẩu mới và mật khẩu nhập lại không giống nhau. Vui lòng nhập lại.";
                        return View();
                    }
                    data.Password = lg.NewPassword;
                    db.SaveChanges();
                    return RedirectToAction("ChangePasswordSuccess");

                }
                ViewBag.mess = "Bạn chưa đăng nhập";
                return RedirectToAction("LogOn");
            }
            return View();
        }

        public ActionResult ChangePasswordSuccess()
        { 
            return View();
        }


        public ActionResult EditInfo()
        {
            if (Session["Login"] == null)
            {
                return RedirectToAction("LogOn");
            }
            MobileWebContext db = new MobileWebContext();
            string str = Session["Login"].ToString();
            var account = db.Accounts.Where(a => (a.UserName == str)).Single();
            account.Password = null;
            return View(account);
        }
        [HttpPost]
        public ActionResult EditInfo(Account ac)
        {
            if ((Session["Login"] == null) || (Session["Login"].ToString() != ac.UserName))
            {
                return RedirectToAction("LogOn");
            }
            MobileWebContext db = new MobileWebContext();
            string str = Session["Login"].ToString();
            int? id = db.Accounts.Find(ac.ID).RoleID;
            if (db.Accounts.Find(ac.ID).Password != ac.Password)
            {
                ViewBag.mess = "Mật khẩu sai";
                return View();
            }
            db.Dispose();
            db = new MobileWebContext();
            if (ModelState.IsValid)
            {
                ac.RoleID = id;
                db.Entry(ac).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("EdiInfoSuccessfull");
            }

            var account = db.Accounts.Where(a => (a.UserName == str)).Single();
            account.Password = null;
            return View(account);
        }
        public ActionResult EdiInfoSuccessfull()
        {
            return View();
        }

        public ActionResult getPassWord()
        {
            if (Session["Login"] != null)
            {
                RedirectToAction("LogOut");
            }
            return View();
        }
        [HttpPost]
        public ActionResult getPassWord(string UserName, string SecretQuestion)
        {
            if (Session["Login"] != null)
            {
                RedirectToAction("LogOut");
            }
            MobileWebContext db = new MobileWebContext();
            var acc = db.Accounts.Where(a => (a.UserName == UserName) && (a.SecretQuestion == SecretQuestion));
            if (acc.Count() > 0)
            {
                ViewBag.pass = acc.Single().Password;    
            }
            else
            {
                ViewBag.mess = "Bạn đã nhập sai username hoặc cụm từ gợi nhớ mật khẩu.";
            }
            
            return View();
        }

        public ActionResult LogOut()
        {
            Session["Login"] = null;
            Session["Roles"] = null;
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Welcome()
        {
            return View();
        }       
    }
}
